package com.atguigu.gmall.mq.config.component.impl;

import com.atguigu.gmall.common.util.JSONs;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.mq.config.component.RabbitService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @Author:lyd
 * @Date:2023/9/5 19:27
 * @Version:1.0
 * @Description
 **/
@Slf4j
@Service
public class RabbitServiceImpl implements RabbitService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;


    @Override
    public void sendMsg(String exchange, String rk, Object msg) {
        String jsonStr = JSONs.toJSONStr(msg);
        rabbitTemplate.convertAndSend(exchange, rk, jsonStr);
    }

    /**
     * 重试，继续关单
     *
     * @param msg
     * @param channel
     * @param deliveryTag
     * @param retryCount
     */
    @Override
    public void reTry(String msg, Channel channel, long deliveryTag, int retryCount) throws IOException {
        String encrypt = MD5.encrypt(msg);
        //存入redis，记录重试的次数
        Long increment = redisTemplate.opsForValue().increment("msg:count:" + encrypt);
        if (increment <= 5) {
            //继续重试处理消息
            channel.basicReject(deliveryTag, true);
        }else {
            //重试5次都不行，记录数据库，让人工处理。重死信队列中删除消息
            channel.basicAck(deliveryTag, false);
            log.warn("消息重试5次后依然消费失败，【存入数据库】，等待人工处理。。。内容：{}", msg);
            redisTemplate.delete("msg:count:" + encrypt);
        }
    }
}
